﻿using System;
using System.Text;
using System.Collections;
using RAP.Framework.Libary.Utils;
using RAP.Framework.Libary.DomTemplateBuilder.Element.Collection;
using RAP.Framework.Libary.DomTemplateBuilder.Element.Collection.TimeIterate;
using RAP.Framework.Libary.DomTemplateBuilder.Interface;

namespace RAP.Framework.Libary.DomTemplateBuilder.Handler.TimeIterate
{
	/// <summary>
	/// 时间迭代器的Handler
	/// </summary>
	public class TimeIterateBaseHandler : IterateHandler
	{
		public const string TIME_ID_FIELD = "TimeId";
		public const string WEEK_ID_FIELD = "WeekId";
		public const string WEEK_FIELD = "Week";
    public const string MONTH_ID_FIELD = "MonthId";
    public const string MONTH_FIELD = "Month";
    public const string QUARTER_ID_FIELD = "QuarterId";
		public const string QUARTER_FIELD = "Quarter";
    public const string YEAR_ID_FIELD = "YearId";
		public const string START_DATE_FIELD = "StartDate";
		public const string END_DATE_FIELD = "EndDate";
    public const string IS_CURRENT_TIME_FIELD = "IsCurrent";

		public new TimeIterateBase Element
		{
			get
			{
				return base.Element as TimeIterateBase;
			}
			set
			{
				base.Element = value as Iterate;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="writer"></param>
		/// <param name="rootParamObject"></param>
		/// <param name="parentParamObject"></param>
		/// <param name="context"></param>
		/// <returns></returns>
		public override void DoRender ( StringBuilder writer, object rootParamObject, object parentParamObject, ITemplateRenderContext context )
		{
			var startDate = GetPropertyValue
			(
				GetPropertyName ( Element.StartDate, rootParamObject, parentParamObject, context )
				, rootParamObject
				, parentParamObject
				, context
			).IsNullValue ( string.Empty )
			.ToString ( )
			.ToDateTimeValue ( );

			if ( startDate.Value.IsNullOrEmpty ( ) )
			{
				throw new NullReferenceException ( "TimeIterate配置节点的开始时间值不能为空！" );
			}
			var endDate = GetPropertyValue
			(
				GetPropertyName ( Element.EndDate, rootParamObject, parentParamObject, context )
				, rootParamObject
				, parentParamObject
				, context
			).IsNullValue ( string.Empty )
			.ToString ( )
			.ToDateTimeValue ( DateTime.Now );
			var list = CreateTimeList ( startDate.Value, endDate.Value );
			RenderCollection ( writer, list, rootParamObject, parentParamObject, context );
		}

		protected virtual IList CreateTimeList ( DateTime start, DateTime end )
		{
			return null;
		}
	}
}
